<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header">
        <span>试题录入</span>
      </div>
      <div class="text item">
        <!-- 表单区域 -->
        <el-form
          ref="testFormRef"
          :model="testForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 学科 -->
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              placeholder="请选择"
              v-model="testForm.subjectID"
              @focus="getSubjectList"
              @change="subjectChange"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 目录 -->
          <el-form-item label="目录:" prop="catalogID">
            <el-select placeholder="请选择" v-model="testForm.catalogID">
              <el-option
                v-for="item in catalogList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 企业 -->
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select
              placeholder="请选择"
              v-model="testForm.enterpriseID"
              @focus="getEnterpriseList"
            >
              <el-option
                v-for="item in enterpriseList"
                :key="item.value"
                :label="item.company"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 城市 -->
          <el-form-item label="城市:" prop="city">
            <el-select
              class="city"
              placeholder="请选择"
              v-model="testForm.province"
              @focus="getProvinceList"
              @change="provinceChange"
            >
              <el-option
                v-for="(item, index) in provinceList"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
            <el-select
              placeholder="请选择"
              v-model="testForm.city"
              class="city"
            >
              <el-option
                v-for="(item, index) in cityList"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 方向 -->
          <el-form-item label="方向:" prop="direction">
            <el-select
              placeholder="请选择"
              v-model="testForm.direction"
              @focus="getDirectionList"
            >
              <el-option
                v-for="(item, index) in directionList"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 题型 -->
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group
              v-model="testForm.questionType"
              @change="questionTypeChange"
            >
              <el-radio
                v-for="item in questionTypeList"
                :key="item.value"
                :label="item.value"
                :value="item.value"
              >
                {{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>

          <!-- 难度 -->
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="testForm.difficulty">
              <el-radio
                v-for="item in difficultyList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 题干 -->
          <!-- 富文本编辑器 -->
          <el-form-item label="题干:" prop="question">
            <quillEditor
              v-model="testForm.question"
              ref="questionQuillEditor"
              :options="editorOption"
            ></quillEditor>
          </el-form-item>

          <!-- 选项 -->
          <el-form-item label="选项:" prop="resource">
            <!-- 多选题 -->
            <template
              v-if="testForm.questionType && testForm.questionType == 2"
            >
              <el-checkbox-group v-model="rightAnswer">
                <div v-for="(item, index) in testForm.options" :key="index">
                  <el-checkbox :label="item.code" class="option-radio">
                    {{ item.code }}:
                    <el-input placeholder="请输入选项" v-model="item.title">
                    </el-input>
                    <div @click.prevent="() => {}">
                      <!-- 图片上传 -->
                      <el-upload
                        action="https://jsonplaceholder.typicode.com/posts/"
                        list-type="picture-card"
                      >
                        上传图片
                      </el-upload>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </template>

            <!-- 简答题 -->
            <template
              v-else-if="testForm.questionType && testForm.questionType == 3"
            >
              <el-input type="textarea" v-model="testForm.options.title">
              </el-input>
            </template>
            <!-- 单选题 -->
            <template v-else>
              <div v-for="(item, index) in testForm.options" :key="index">
                <el-radio
                  v-model="rightAnswer"
                  :label="item.code"
                  class="option-radio"
                >
                  {{ item.code }}:
                  <el-input
                    placeholder="请输入选项"
                    v-model="item.title"
                  ></el-input>
                  <!-- 图片上传 -->
                  <div @click.prevent="() => {}">
                    <el-upload
                      action="https://jsonplaceholder.typicode.com/posts/"
                      list-type="picture-card"
                    >
                      上传图片
                    </el-upload>
                  </div>
                </el-radio>
              </div>
            </template>
            <el-row>
              <el-button
                icon="el-icon-plus"
                class="affirmBtn"
                type="danger"
                v-if="testForm.questionType !== 3"
                :disabled="testForm.questionType !== 2"
                @click="addOptions"
              >
                增加选项与答案
              </el-button>
            </el-row>
          </el-form-item>

          <!-- 解析视频 -->
          <el-form-item label="解析视频:" :prop="testId ? 'videoURL' : ''">
            <el-input
              placeholder=""
              class="video"
              v-model="testForm.videoURL"
            ></el-input>
          </el-form-item>

          <!-- 富文本编辑器 -->
          <!-- -->
          <el-form-item label="答案解析:" prop="answer">
            <quillEditor
              v-model="testForm.answer"
              :options="editorOption"
              @blur="$refs.testFormRef.validateField('answer')"
            ></quillEditor>
          </el-form-item>

          <el-form-item label="题目备注:" :prop="testId ? 'remarks' : ''">
            <el-input type="textarea" :rows="5" v-model="testForm.remarks">
            </el-input>
          </el-form-item>

          <el-form-item label="试题标签:">
            <el-select placeholder="请选择" v-model="testForm.tags" multiple>
              <el-option
                v-for="item in tagsList"
                :key="item.id"
                :label="item.tagName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-button
          class="affirmBtn"
          :type="testId ? 'success' : 'primary'"
          @click="addTest"
          >{{ testId ? "确认修改" : "确认提交" }}</el-button
        >
      </div>
    </el-card>

    <!-- 弹出层 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
// 导入富文本编辑器 样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入富文本编辑器
import { quillEditor } from 'vue-quill-editor'

// 导入请求---------------------------------
// 学科列表
import { simple } from '@/api/hmmm/subjects.js'
// 目录
import { simple as directorysList } from '@/api/hmmm/directorys.js'
// 企业
import { list as enterpriseList } from '@/api/hmmm/companys.js'
// 城市
import { provinces, citys } from '@/api/hmmm/citys.js'
// 常量数据
import { difficulty, questionType, direction } from '@/api/hmmm/constants.js'
// 标签获取
import { list as tagsList } from '@/api/hmmm/tags.js'
// 添加题库
import { add as addTest, detail as editQuestions, update as updateQuestions } from '@/api/hmmm/questions.js'
export default {
  name: 'questions',
  data () {
    return {
      // 试题ID
      testId: '',
      testForm: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '',
        // 难度
        difficulty: '',
        // 题干
        question: '',
        // 选项
        options: [
          {
            code: 'A', // 非必须代码例如:A或B或C...
            title: '', // 非必须标题
            img: '', // 非必须图片URL
            isRight: ''// 非必须是否正确答案
          },
          {
            code: 'B', // 非必须代码例如:A或B或C...
            title: '', // 非必须标题
            img: '', // 非必须图片URL
            isRight: ''// 非必须是否正确答案
          },
          {
            code: 'C', // 非必须代码例如:A或B或C...
            title: '', // 非必须标题
            img: '', // 非必须图片URL
            isRight: ''// 非必须是否正确答案
          },
          {
            code: 'D', // 非必须代码例如:A或B或C...
            title: '', // 非必须标题
            img: '', // 非必须图片URL
            isRight: ''// 非必须是否正确答案
          }

        ],
        // 视频解析
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: []
      },
      rules: {
        subjectID: [
          { required: true, message: '该项必填', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '该项必填', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '该项必填', trigger: 'change' }
        ],
        city: [
          { required: true, message: '该项必填', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '该项必填', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '该项必填', trigger: 'change' }
        ],

        difficulty: [
          { required: true, message: '该项必填', trigger: 'change' }
        ],
        question: [
          { required: true, message: '该项必填', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '该项必填', trigger: 'blur' }
        ],
        videoURL: [
          { required: true, message: '该项必填', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '该项必填', trigger: 'blur' }
        ]

      },
      // 学科列表
      subjectList: [],
      // 目录列表
      catalogList: [],
      // 企业列表
      enterpriseList: [],
      // 城市列表
      provinceList: [],
      // 地区列表
      cityList: [],
      // 方向列表
      directionList: [],
      // 题型列表
      questionTypeList: [],
      // 难度列表
      difficultyList: [],
      // 弹出层显示与隐藏
      dialogVisible: false,
      // 图片显示的地址
      dialogImageUrl: '',
      // 单选正确答案
      rightAnswer: [],
      // 试题标签
      tagsList: [],
      // 备份选项数据
      currentOptions: [],
      // 当前题型
      currentQuestionType: '',
      // 当前正确项
      currentRightAnswer: [],

      // 富文本编辑器

      editorOption: {
        // 主题
        theme: 'snow',
        placeholder: '请输入正文'
      }

    }
  },
  async  created () {
    this.difficultyList = difficulty
    this.questionTypeList = questionType
    this.testId = parseInt(this.$route.query.id)

    if (this.testId) {
      // 处理修改数据函数
      this.getDetail()
    }
  },
  components: {
    quillEditor
  },
  watch: {
    rightAnswer (val) {
      if (typeof val === 'object') {
        this.testForm.options.forEach(item => {
          item.isRight = val.includes(item.code)
        })
      } else {
        this.testForm.options.forEach(item => {
          if (item.code === val) {
            item.isRight = true
          } else {
            item.isRight = false
          }
        })
      }
    }
  },
  methods: {
    // 获取学科----------------------------
    async getSubjectList () {
      const { data } = await simple()
      this.subjectList = data
    },

    // 获取目录 学科的change事件----------------------------
    async subjectChange () {
      // 清空目录 因为目录的数据依赖 学科id 当学科id发生改变就先清空数据
      this.testForm.catalogID = ''

      // 获取目录
      const { data: catalogList } = await directorysList({
        subjectID: this.testForm.subjectID
      })
      this.catalogList = catalogList
      // 获取试题标签
      const { data: { items } } = await tagsList(this.testForm.subjectID)
      this.tagsList = items
    },

    // 获取企业列表------------------------
    async getEnterpriseList () {
      const { data: { items } } = await enterpriseList()
      this.enterpriseList = items
    },

    // 获取城市---------------------------
    getProvinceList () {
      this.provinceList = provinces()
    },

    //  城市下拉框change事件-----------------
    provinceChange () {
      this.cityList = citys(this.testForm.province)
    },

    // 获取方向----------------------------
    getDirectionList () {
      this.directionList = direction
    },

    // 新增选项----------------------------
    addOptions () {
      const num = this.testForm.options[this.testForm.options.length - 1].code.charCodeAt(0) + 1
      const newCode = String.fromCharCode(num)
      this.testForm.options.push(
        {
          code: newCode, // 非必须代码例如:A或B或C...
          title: '', // 非必须标题
          img: '', // 非必须图片URL
          isRight: ''// 非必须是否正确答案
        })
    },

    // 题型改变事件
    questionTypeChange (val) {
      // 如果有id
      if (this.testId) {
        if ((val + '') === this.currentQuestionType) {
          this.rightAnswer = this.currentRightAnswer
          console.log('', this.rightAnswer)
          this.testForm.options = this.currentOptions
        } else {
          this.rightAnswer = []
          this.testForm.options = this.$options.data().testForm.options
        }
      } else {
        // 渲染正确选项
        this.rightAnswer = []
      }
    },

    // 添加试题
    async addTest () {
      try {
        // 校验表单
        await this.$refs.testFormRef.validate()
        this.testForm.tags = this.testForm.tags.join()
        this.testForm.questionType = this.testForm.questionType + ''
        if (this.testId) {
          await updateQuestions(this.testForm)
        } else {
          await addTest(this.testForm)
        }
        this.$message({
          message: this.testId ? '修改试题成功' : '新增试题成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
      } catch (error) {
        console.log(error)
      }
    },

    // 修改试题方法
    async getDetail () {
      // 获取试题详情
      const { data } = await editQuestions({ id: this.testId })
      console.log(data)
      this.testForm = data
      // 保存当前题型
      this.currentQuestionType = this.testForm.questionType
      // 保存当前选项
      this.currentOptions = this.testForm.options

      // 转换数据
      this.testForm.tags = this.testForm.tags.split(',')
      this.testForm.tags = this.testForm.tags.map(t => parseInt(t))
      this.testForm.questionType = parseInt(this.testForm.questionType)

      // 获取学科列表
      this.getSubjectList()

      // 获取企业列表
      this.getEnterpriseList()

      // 获取目录
      const { data: catalogList } = await directorysList({
        subjectID: this.testForm.subjectID
      })
      this.catalogList = catalogList

      // 获取试题标签
      const { data: { items } } = await tagsList(this.testForm.subjectID)
      this.tagsList = items

      // 获取题型
      this.questionTypeList = questionType

      if (this.testForm.questionType === 1) {
        this.testForm.options.forEach(item => {
          if (item.isRight === 1) {
            this.rightAnswer = item.code
          }
        })
      } else if (this.testForm.questionType === 2) {
        // 处理选项数据
        this.testForm.options.forEach(item => {
          if (item.isRight === 1) {
            this.rightAnswer.push(item.code)
          }
        })
      }
      this.currentRightAnswer = this.rightAnswer
    }

  }
}
</script>

<style scoped lang='scss'>
.box-card {
  margin: 15px;
}
.affirmBtn {
  margin-left: 55px;
}
::v-deep .el-form-item__content .el-select {
  width: 25%;
}
::v-deep .options {
  .el-radio__label {
    display: flex;
  }
}
.option-radio {
  margin: 25px;
}
::v-deep .el-textarea__inner {
  width: 25%;
}
.video {
  width: 25%;
}
::v-deep .el-form-item__content .city {
  width: 12%;
  margin: 0 5px;
}
::v-deep .el-upload {
  position: absolute;
  top: -13px;
  left: 300px;
  height: 50px;
  line-height: 50px;
  margin-top: 5px;
}
</style>
